﻿using Microsoft.Win32;
using movie.tool.library.hash;
using movie.tool.library.ui;
using movie.tool.module.film.model;
using movie.tool.module.film.service;
using movie.tool.module.http;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;

namespace movie.tool.module.film.ui
{
    /// <summary>
    /// PlayRoleInfoControl.xaml 的交互逻辑
    /// </summary>
    public partial class PlayRoleInfoControl : BaseControl
    {
        public static readonly DependencyProperty ConfigProperty = DependencyProperty.Register("Config", typeof(MovieProject), typeof(PlayRoleInfoControl));
        public MovieProject Config
        {
            get => (MovieProject)GetValue(ConfigProperty);
            set => SetValue(ConfigProperty, value);
        }
        public static readonly DependencyProperty BusyInfoProperty = DependencyProperty.Register("BusyInfo", typeof(BusyInfo), typeof(PlayRoleInfoControl));
        public BusyInfo BusyInfo
        {
            get => (BusyInfo)GetValue(BusyInfoProperty);
            set => SetValue(BusyInfoProperty, value);
        }
        private PlayerRoleConfig currentRole;
        public PlayerRoleConfig CurrentRole
        {
            get => currentRole;
            set
            {
                currentRole = value;
                SendPropertyChanged(nameof(CurrentRole));
            }
        }
        /// <summary>
        /// 添加、删除和保存的按钮是否可见
        /// </summary>
        public Visibility ModifyVisible
        {
            get
            {
                if (Config != null && Config.ImportProject)
                {
                    return Visibility.Collapsed;
                }
                return Visibility.Visible;
            }
        }
        public PlayRoleInfoControl()
        {
            InitializeComponent();
        }

        private async void AddPlayRoleClick(object sender, RoutedEventArgs e)
        {
            if (BusyInfo.Busy)
            {
                return;
            }
            try
            {
                BusyInfo.Busy = true;
                BusyInfo.DefaultMessage();
                if (Config.Roles == null)
                {
                    Config.Roles = new ObservableCollection<PlayerRoleConfig>();
                }
                PlayerRoleConfig param = new PlayerRoleConfig();
                param.Name = "新建角色";
                param.Gender = "男";
                param.CrossGender = "不可";
                long? id = await MovieClient.SavePlayerRole(param, Config.Id);
                if(id != null && id > 0)
                {
                    param.Id = (long)id;
                    CurrentRole = param;
                    Config.Roles.Add(param);
                    MovieService.SaveProjectMovie(Config);
                }
            }
            finally
            {
                BusyInfo.Reset();
            }
        }

        private async void DeletePlayRoleClick(object sender, RoutedEventArgs e)
        {
            if (BusyInfo.Busy)
            {
                return;
            }
            try
            {
                BusyInfo.Busy = true;
                BusyInfo.DefaultMessage();
                if (CurrentRole == null)
                {
                    MessageBox.Show("请选择角色");
                    return;
                }
                bool ret = await HttpInvoker.DeleteAsync("movieserver/playRoles/" + CurrentRole.Id);
                if (ret)
                {
                    Config.Roles.Remove(CurrentRole);
                    CurrentRole = null;
                    MovieService.SaveProjectMovie(Config);
                }
            }
            finally
            {
                BusyInfo.Reset();
            }
        }

        private void RoleBrowserClick(object sender, RoutedEventArgs e)
        {
            if (BusyInfo.Busy)
            {
                return;
            }
            if (CurrentRole == null)
            {
                MessageBox.Show("请选择一个角色再操作");
                return;
            }
            try
            {
                BusyInfo.Busy = true;
                BusyInfo.DefaultMessage();
                OpenFileDialog dialog = new OpenFileDialog();
                //选择角色文件
                dialog.Filter = "图片文件(*.png,*.jpg,*.jpeg,*.bmp)|*.png;*.jpg;*.jpeg;*.bmp";
                dialog.Title = "选择角色文件";

                if (!string.IsNullOrEmpty(CurrentRole.FilePath))
                {
                    string filePath = Path.Join(MovieService.ProjectJsonFilePath(Config.Id), CurrentRole.FilePath);
                    dialog.InitialDirectory = Path.GetDirectoryName(filePath);
                }

                bool? result = dialog.ShowDialog();
                if (result != null && result == true)
                {
                    string rootPath = MovieService.ProjectJsonFilePath(Config.Id);
                    if (dialog.FileName.StartsWith(rootPath))
                    {
                        //选择的文件在项目目录下,那就不用复制了
                        CurrentRole.FilePath = Path.GetRelativePath(rootPath, dialog.FileName);
                    }
                    else
                    {
                        string path = Path.Combine(rootPath, "roles");
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        path = Path.Combine(path, Path.GetFileName(dialog.FileName));
                        if (File.Exists(path))
                        {
                            string selectDigest = SHA1Hash.FileDigest(dialog.FileName);
                            string targetDigest = SHA1Hash.FileDigest(path);
                            if (!selectDigest.Equals(targetDigest))
                            {
                                MessageBox.Show("文件" + path + "已经存在,无法复制,请选择不同名称的文件");
                                return;
                            }
                            else
                            {
                                //相同,不需要复制
                                CurrentRole.FilePath = Path.GetRelativePath(rootPath, path);
                            }
                        }
                        else
                        {
                            File.Copy(dialog.FileName, path);
                            CurrentRole.FilePath = Path.GetRelativePath(rootPath, path);
                        }
                    }
                    if ("新建角色".Equals(CurrentRole.Name))
                    {
                        string name = Path.GetFileNameWithoutExtension(CurrentRole.FilePath);
                        if (!string.IsNullOrWhiteSpace(name))
                        {
                            CurrentRole.Name = name;
                        }
                    }
                }
            }
            finally
            {
                BusyInfo.Reset();
            }
        }

        private async void PlayRoleSubmitClick(object sender, RoutedEventArgs e)
        {
            if (BusyInfo.Busy)
            {
                return;
            }
            try
            {
                if(CurrentRole == null)
                {
                    MessageBox.Show("请选择一个角色再操作");
                    return;
                }
                BusyInfo.Busy = true;
                BusyInfo.DefaultMessage();
                bool ret = await MovieClient.UpdatePlayerRole(currentRole);
                if (ret)
                {
                    //查看文件是否修改
                    if (!string.IsNullOrEmpty(CurrentRole.FilePath))
                    {
                        string rootPath = MovieService.ProjectJsonFilePath(Config.Id);
                        string filePath = Path.Join(rootPath, CurrentRole.FilePath);

                        if (File.Exists(filePath))
                        {
                            if (!await MovieClient.PlayerRoleFileEquals(filePath, CurrentRole.Id))
                            {
                                //文件不一样,那上传文件
                                bool res = await MovieClient.UploadPlayerRoleFile(filePath,CurrentRole.Id, CurrentRole.FilePath);
                                if (res)
                                {
                                    MessageBox.Show("提交成功");
                                }
                                else
                                {
                                    MessageBox.Show("角色信息保存成功,文件上传失败");
                                }
                            }
                            else
                            {
                                MessageBox.Show("提交成功");
                            }
                        }
                        else
                        {
                            MessageBox.Show("提交成功");
                        }
                    }
                    else
                    {
                        MessageBox.Show("提交成功");
                    }
                }
            }
            finally
            {
                BusyInfo.Reset();
            }
        }

        private void BaseControl_Loaded(object sender, RoutedEventArgs e)
        {
            SendPropertyChanged(nameof(ModifyVisible));
        }

        private async void RoleDownloadClick(object sender, RoutedEventArgs e)
        {
            if (BusyInfo.Busy || CurrentRole==null)
            {
                return;
            }
            try
            {
                BusyInfo.Busy = true;
                BusyInfo.BusyMessage = "下载中...";
                string rootPath = MovieService.ProjectJsonFilePath(Config.Id);
                await MovieSynchronizer.SyncPlayRoleFile(rootPath,CurrentRole);
            }
            finally
            {
                BusyInfo.Reset();
            }
        }
    }
}
